package com.rpoonolly.simplegame.mapio.jsoncoders;

import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.rpoonolly.simplegame.worldGrid.WorldGrid;
import com.rpoonolly.simplegame.worldGrid.WorldGridTile;

public class WorldGridJSONCoder extends JSONCoder<WorldGrid> {
	private static WorldGridJSONCoder singletonInstance = null;
	private WorldGridTileJSONCoder tileCoder = WorldGridTileJSONCoder.getInstance();
	
	private WorldGridJSONCoder() {}

	@SuppressWarnings("unchecked")
	@Override
	public JSONObject encode(WorldGrid grid) throws IOException {
		JSONObject jsonGrid = new JSONObject();
		
		JSONArray jsonTiles = new JSONArray();		
		for(WorldGridTile tile : grid.getSavedTiles()) {
			jsonTiles.add(tileCoder.encode(tile));
		}
		
		jsonGrid.put("tiles", jsonTiles);
		jsonGrid.put("originX", grid.getOriginX());
		jsonGrid.put("originY", grid.getOriginY());
		jsonGrid.put("gridCellWidth", grid.getGridCellWidth());
		jsonGrid.put("gridCellHeight", grid.getGridCellHeight());
		
		return jsonGrid;
	}

	@Override
	public WorldGrid decode(JSONObject jsonGrid) throws IOException {
		int originX = (Integer) jsonGrid.get("originX");
		int originY = (Integer) jsonGrid.get("originY");
		int gridCellWidth = (Integer) jsonGrid.get("gridCellWidth");
		int gridCellHeight = (Integer) jsonGrid.get("gridCellHeight");
		
		WorldGrid grid = new WorldGrid(originX, originY, gridCellWidth, gridCellHeight);
		JSONArray jsonTiles = (JSONArray) jsonGrid.get("tiles");
		
		JSONObject jsonTile;
		for(Object obj : jsonTiles) {
			jsonTile = (JSONObject) obj;
			grid.putTile(tileCoder.decode(jsonTile));
		}
		
		return grid;
	}

	public static WorldGridJSONCoder getInstance() {
		if (singletonInstance == null)
			singletonInstance = new WorldGridJSONCoder();
		
		return singletonInstance;
	}
}
